package org.an.proj.contacts.util;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

public class DeviceUtil {

  private DeviceUtil() {
    throw new AssertionError("No instance!");
  }

  public static String mapToString(Map<String, String> map) {
    StringBuffer sb = new StringBuffer();

    for (Map.Entry<String, String> entry : map.entrySet()) {
      String key = entry.getKey();
      String value = entry.getValue();
      sb.append(key).append(" = ").append(value).append("\n");
    }

    return sb.toString();
  }

  /**
   * 获取一些简单的信息,软件版本，手机版本，型号等信息
   */
  public static Map<String, String> obtainSimpleInfo(Context context) {
    Map<String, String> map = new HashMap<>();
    PackageManager mPackageManager = context.getPackageManager();
    PackageInfo mPackageInfo = null;
    try {
      mPackageInfo =
          mPackageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }

    if (mPackageInfo != null) {
      map.put("versionName", mPackageInfo.versionName);
      map.put("versionCode", "" + mPackageInfo.versionCode);
    }
    map.put("MODEL", "" + Build.MODEL);
    map.put("SDK_INT", "" + Build.VERSION.SDK_INT);
    map.put("PRODUCT", "" + Build.PRODUCT);

    return Collections.unmodifiableMap(map);
  }

  /**
   * 获取手机唯一识别码
   * Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE
   *
   * @return 手机唯一识别码
   */
  public static String getUUID(Context context) {
    SharedPreferences sp =
        context.getApplicationContext().getSharedPreferences("config", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    String deviceId = sp.getString("IDID", "").trim();

    if (TextUtils.isEmpty(deviceId)) {
      // 如果config文件中没有存储IDID，则需要重新获取IDID,首先考虑deviceId
      // fixme 使用隐私权限前必须校验
      if (AppUtil.checkPermission(Manifest.permission.READ_PHONE_STATE)) {
        TelephonyManager tm =
            (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        // fixme 这个要怎么做权限申请呢?放到闪屏页去申请权限
        deviceId = tm != null ? trim(tm.getDeviceId()) : "";
      }

      // 如果没有获取到deviceId,则通过getMyUUID获取
      if (TextUtils.isEmpty(deviceId) || "000000000000000".equals(deviceId)) {
        // deviceId = getMyUUID();
        OpenUDIDManager.sync(context);
        if (OpenUDIDManager.isInitialized()) {
          deviceId = OpenUDIDManager.getOpenUDID();
        }
        if (TextUtils.isEmpty(deviceId)) {
          UUID uuid = UUID.randomUUID();
          String uuidString = uuid.toString();
          if (!TextUtils.isEmpty(uuidString) && uuidString.contains("-")) {
            uuidString = uuidString.replace("-", "");
          }
          deviceId = uuidString;
        }

        if (TextUtils.isEmpty(deviceId)) {
          // 产生一个8位随机数(10000000~99999999)
          Random random = new Random();
          int randomNum = random.nextInt(89999999) + 10000000;
          deviceId = String.valueOf(randomNum);
        }
      }

      // 保存到config文件中
      editor.putString("IDID", deviceId);
      editor.apply();
    }
    return trim(deviceId);
  }

  public static String getUserAgent(Context context) {
    return "HomeLink "
        + getAppVersion(context)
        + ";"
        + Build.BRAND
        + " "
        + Build.MODEL
        + "; Android "
        + Build.VERSION.RELEASE;
  }

  public static String getAppVersion(Context context) {
    try {
      PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
      // 当前应用的版本名称
      // String versionName = info.versionName;
      // // 当前版本的版本号
      // int versionCode = info.versionCode;
      // // 当前版本的包名
      // String packageNames = info.packageName;
      return info.versionName;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  public static String trim(String text) {
    return TextUtils.isEmpty(text) ? "" : text.trim();
  }
}
